<?php

namespace common\models;

use common\helpers\commonApi;
use Yii;

/**
 * This is the model class for table "{{%goods_spec}}".
 *
 * @property int $id
 * @property int|null $good_id 商品id
 * @property string|null $name 规格名称
 * @property float|null $original_price 原价
 * @property float|null $price 现价
 * @property string|null $create_time 创建时间
 * @property string|null $update_time 修改时间
 * @property float|null $trade_price 批发价
 * @property float|null $ca_price 校区价
 */
class GoodsSpec extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%goods_spec}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['good_id'], 'integer'],
            [['original_price', 'price','trade_price','ca_price'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'good_id' => '商品id',
            'name' => '规格名称',
            'original_price' => '原价',
            'price' => '现价',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'trade_price' => '批发价',
            'ca_price' => '校区价',
        ];
    }

    /**
     * 此方法只支持同一个校区的商品
     * @param array $goods
     * @return array
     */
    public function calculation(array $goods,$is_cart=0,$delivery_method)
    {
        foreach ($goods as &$good){
            if (empty($good['campus_id'])){
                return commonApi::message('请选择校区',false);
            }
            if (empty($good['g_id'])){
                return commonApi::message('商品编号不存在',false);
            }
            if (empty($good['spec_id'])){
                return commonApi::message('规格编号不存在',false);
            }
            if (empty($good['num'])){
                return commonApi::message('请选择购买数量',false);
            }
            if (!preg_match("/^[1-9][0-9]*$/" ,$good['num'])){
                return commonApi::message('购买数量必须是整数',false);
            }
            $good['good_id'] = $good['g_id'];
            $good['mark'] = $good['good_id'].'_'.$good['spec_id'];
            $good['mark_stock'] = $good['campus_id'].'_'.$good['good_id'].'_'.$good['spec_id'];
        }
        $markArr = array_column($goods,null,'mark');
        $markStock = array_column($goods,'mark_stock');//库存
        $goods_id = array_column($goods,'good_id');
        $spec_id = array_column($goods,'spec_id');
        $goodsSpec = Goods::find()
            ->where(['id'=>$goods_id,'delete'=>0])
            ->with([
                'spec' => function ($query)use($spec_id){
                    $query->where(['id'=>$spec_id]);
                }
            ])
            ->asArray()->all();
        //库存
        $goodsstock = GoodsStock::find()->where(['mark'=>$markStock])->asArray()->all();
        $goodsstock = array_column($goodsstock,'stock','mark');
        $goods_total = [
            'total_amount'=>0,//商品总价
            'discount_amount'=>0,//优惠金额
            'delivery_fee'=>0,//配送费
            'pay_amount'=>0,//支付金额
            'total_num'=>0,//总数
            'trade_price'=>0,//批发价
            'ca_price'=>0,//校区价
        ];
        $goodsNum = 0;
        $goods_spec = [];
        foreach ($goodsSpec as $value){
            unset($value['details']);
            $goodsNum += 1;
            foreach ($value['spec'] as $item){
                $mark = $value['id'].'_'.$item['id'];
                $is_buy = 1;
                if (empty($markArr[$mark])){
                    if (!$is_cart){
                        return commonApi::message("【{$value['name']}】的规格不存在",false);
                    }else{
                        continue;
                    }
                }
                $stock = $markArr[$mark]['mark_stock'];//当前校区商品总库存标记
                $num = $markArr[$mark]['num'];//我购买商品的数量
                if (!isset($goodsstock[$stock])){
                    if (!$is_cart){
                        return commonApi::message("【{$item['name']}】规格库存未设置",false);
                    }else{
                        $is_buy = 0;
//                        continue;
                    }
                }
                if ($goodsstock[$stock]<$num){
                    if (!$is_cart){
                        return commonApi::message("【{$item['name']}】规格库存不足",false);
                    }else{
                        $is_buy = 0;
//                        continue;
                    }
                }
                $price = $item['price']*$num;//计算商品价格
                $trade_price = $item['trade_price']*$num;//计算商品批发价格
                $ca_price = $item['ca_price']*$num;//计算商品校区价格
                $pay_price = 0;
                if ($is_buy){
                    $goods_total['total_num'] += $num;//加上商品数量
                    $goods_total['total_amount'] += $price;//加上商品总价
                    $goods_total['trade_price'] += $trade_price;//批发价
                    $goods_total['ca_price'] += $ca_price;//校区价格
                    $pay_price = $price;//支付金额
                    $goods_total['pay_amount'] += $pay_price;
                }

                $one = [
                    'order_id'=>'order_id_value',
                    'good_id'=>$value['id'],
                    'spec_id'=>$item['id'],
                    'good_name'=>$value['name'],
                    'spec_name'=>$item['name'],
                    'good_info'=>json_encode($value),
                    'spec_info'=>json_encode($item),
                    'good_num'=>$num,
                    'good_price'=>$item['price'],
                    'total_price'=>$price,
                    'pay_price'=>$pay_price,
                    'discount_amount'=>0,
                    'campus_id'=>$markArr[$mark]['campus_id'],
                    'trade_price'=>$trade_price,
                    'ca_price'=>$ca_price,
                ];
                if ($is_cart){
                    $one['main_img'] = $value['main_img'];
                    $one['stock'] = $goodsstock[$stock]??0;
                    $one['mark'] = $mark;
                    $one['is_buy'] = $is_buy;
                }
                $goods_spec[] = $one;
            }
        }
        $delivery_fee = 0;
        if ($delivery_method==2){
            $delivery_fee = $this->deliveryFee($goods_total['total_num'],$goodsNum);
        }
        $goods_total['delivery_fee'] = $delivery_fee;
        $goods_total['pay_amount'] += $delivery_fee;
        $data = [
            'goods_total'=>$goods_total,
            'goods_spec'=>$goods_spec,
        ];
        return commonApi::message('ok',true,$data);
    }

    /**
     * 计算配送费
     * @param $num 用户所选商品的总件数
     * @param $goodNum 用户所选商品的种类
     * @return float|int|mixed
     */
    public function deliveryFee($num,$goodNum)
    {
        $system = System::getModel();
        $start_price = $system->start_price??0;
        $start_num = $system->start_num??0;
        $unit_price = $system->unit_price??0;
        $fee = $start_price;
        if ($num>$start_num){
            $diff = $num-$start_num;
            $diffFee = $diff*$unit_price;
            $fee += $diffFee;
        }
        return $fee;
    }
}
